package com.pro.controller;

import com.pro.pojo.JsonData;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/upload")
public class uploadController extends HttpServlet {

    //上传头像
    private static int i = 0;
    @RequestMapping(value="/uploadFile",method= RequestMethod.POST)
    @ResponseBody
    public JsonData upload(MultipartFile file, HttpSession session) throws IOException {
        //上传原始文件名
        String name = file.getOriginalFilename();
        String path = null;
        //获取上传文件的后缀名
        //String end = name.substring(name.lastIndexOf("."));
        if(file.getSize()>0) {
            //i++;
            //name = i + end;//重新定义上传图像的名字
            //上传图片存放的路径
            path = System.getProperty("user.dir")+"/src/main/resources/static/upload";
            //封装到一个目录
            File f = new File(path, name);
            //将上传的文件存入某个文件夹中
            //文件上传工具类
            FileUtils.copyInputStreamToFile(file.getInputStream(),f);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("fileName",name);//文件上传的名字
        Map<String, Object> data = new HashMap<>();
        data.put("url", ""+ name);
        map.put("data", "/upload"+data);

        return map != null ? JsonData.buildSuccess(map): JsonData.buildError("服务器出错了");
    }

    @RequestMapping(value="/uploadVideo",method= RequestMethod.POST)
    @ResponseBody
    public JsonData uploadVideo(MultipartFile file, HttpSession session){
        String lenth = "";
        return null;
    }

}
